package by.blog.web.filters;

import by.blog.dao.beans.User;
import by.blog.service.UserService;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class AuthFilter implements Filter {
    private UserService userService = null;
    private ServletContext context;

    public void init(FilterConfig fConfig) throws ServletException {
        this.context = fConfig.getServletContext();
        userService = new UserService();
        //this.context.log("AuthenticationFilter initialized");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String uri = req.getRequestURI();
        HttpSession session = req.getSession(false);

        //try {
            if (uri.endsWith("index.jsp")) {
                chain.doFilter(request, response);
            }
            else if (session == null) {
                res.sendRedirect("index.jsp");
            }
            else if (session.getAttribute("user_name") == null) {

                String name = req.getParameter("user_name");
                String pass = req.getParameter("user_pass");

                User user = new User();
                user.setUser_name(name);
                user.setUser_pass(pass);

                boolean check = user.equals(userService.readUnit(name));

                if (check) {

                    session.setAttribute("user_name", name);
                    session.setMaxInactiveInterval(1 * 60);
                    //Cookie userName = new Cookie("user", user.getUser_name());
                    //userName.setMaxAge(30*60);
                    chain.doFilter(request, response);
                } else {
                    res.sendRedirect("index.jsp");
                }
            }
            else {
                chain.doFilter(request, response);
            }
        //}
        //catch (Exception e) {
        //    res.sendRedirect("index.jsp");
        //}
    }

    public void destroy() {
        //close any resources here
    }

}